package converter.gui;

import converter.core.Core;
import converter.core.utils.FileUtil;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

/**
 * Created with IntelliJ IDEA.
 * User: Snark
 * Date: 31.03.13
 * Time: 15:29
 * To change this template use File | Settings | File Templates.
 */
public class MainFrame extends JFrame {

    private JButton     viewButton;
    private JButton     startButton;
    private JTextField  pathTextField;

    public MainFrame() {
        initUI();
        initListeners();
    }

    private void initUI() {
        setLayout(new GridBagLayout());

        viewButton =    new JButton("Обзор");
        add(viewButton,     new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.NONE,          new Insets(5, 5, 5, 5), 0, 0));

        pathTextField = new JTextField();
        pathTextField.setEnabled(false);
        add(pathTextField,  new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.HORIZONTAL,    new Insets(5, 5, 5, 5), 0, 0));

        startButton =   new JButton("Начать");
        add(startButton,    new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0, GridBagConstraints.WEST,
                GridBagConstraints.HORIZONTAL,    new Insets(5, 5, 5, 5), 0, 0));

        setTitle("XConverter");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 100);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initListeners() {
        viewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fileChooser.showOpenDialog(null);
                File selectedFile = fileChooser.getSelectedFile();
                if (selectedFile != null) {
                    pathTextField.setText(selectedFile.getAbsolutePath());
                }
            }
        });

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String path = pathTextField.getText();
                File file = new File(path);
                if (file.isDirectory()) {
                    List<File> fileList = FileUtil.getAllFiles(file);
                    Core.get().convert(fileList);
                }
            }
        });
    }
}
